define(function (require, exports, module) {

/**
 * 上传
 *
 * @module BaseCore
 */

'use strict';

var BaseCore = require('../base/core');

var Setting = require('../../magickimg/setting'),
    Process = require('../../magickimg/process');

var BaseButton = require('../base/button');

var Thumb = require('./thumb');

/**
 * Core
 *
 * @class Core
 * @constructor
 */
var Core = BaseCore.extend({

  defaults: {
    fileName: 'imageFile',
    // 魔图设置
    process: true,
    classPrefix: 'image-upload',
    url: 'imageUpload',
    queueOptions: { },
    selectOptions: {
      accept: 'image/*',
      label: '添加图片',
      // 1M
      maxSize: 5 * 1024 * 1024
    },
    buttonOptions: { }
  },

  setup: function () {
    this.on({
      render: function (e) {
        if (e.target.type === 'Core') {
          if (this.option('process')) {
            // 设置批量处理
            initBatchSetting(e.target);
            // 重写complete
            initComplete(e.target);
            // 添加提交参数
            initProcess(e.target);
          }
        }
        if (e.target.type === 'File') {
          // 显示预览图
          initThumb(e.target, this);
        }
      }
    });

    Core.superclass.setup.apply(this);
  }

});

function initComplete (upload) {
  upload.complete = function (queueFile) {
    var setting = upload.queue.setting,
        settings,
        watermarkData;

    if (setting.is(':hidden')) {
      setting = queueFile.setting;
    }

    settings = setting.get() || {};

    setting.watermarkSelect.data('select')
    .forEach(function (item) {
      if (item.selected) {
        watermarkData = item;
        return true;
      }
    });

    // 魔图
    new Process({
      imageUrl: queueFile.data('remotePath'),
      settings: settings,
      sourceData: {
        width: queueFile.data('width'),
        height: queueFile.data('height')
      },
      watermarkData: watermarkData,
      events: {
        complete: function (e, thumbUrl) {
          queueFile.data('thumbUrl', thumbUrl);
          upload.fire('complete', queueFile, settings);
        },
        error: function (e, msg) {
          upload.fire('error', msg);
        }
      }
    });
  };
}

function initProcess (upload) {
  // from File
  upload.on('formData', function (e) {
    var queueFile = e.target,
        formData = queueFile.formData,
        settings = upload.queue.setting.is(':visible') ?
            upload.queue.setting.get() :
            queueFile.setting.get();

    if (settings) {
      if (settings.tags) {
        formData.append('tags', settings.tags);
      }
      if (settings.remark) {
        formData.append('remark', settings.remark);
      }
    }
  });
}

function initBatchSetting (upload) {
  var queue = upload.queue;

  queue.batch = new BaseButton({
    container: upload.select.element,
    data: {
      icon: 'square-o',
      label: '批量处理'
    },
    delegates: {
      'click': function () {
        if (this.is(':disabled')) {
          return;
        }

        if ((this.actived = !this.actived)) {
          queue.setting.show();
        } else {
          queue.setting.hide();
        }
      }
    },
    insert: function () {
      this.container.after(this.element);
    }
  });

  queue.on({
    queue: function () {
      queue.batch.enable(true);
    },
    empty: function () {
      queue.batch.enable(false);
      queue.setting.hide();
    }
  });

  queue.setting = new Setting({
    container: queue.element,
    hasLink: upload.option('hasLink'),
    insert: function () {
      this.container.before(this.element);
    },
    events: {
      show: function () {
        queue.element.addClass('short');
        // 隐藏其他
        queue.getFiles().forEach(function (queueFile) {
          queueFile.setting &&
          queueFile.setting.is(':visible') &&
          queueFile.setting.hide();
        });
        queue.batch.$('span').attr('class', 'fa fa-check-square-o');
      },
      hide: function () {
        queue.element.removeClass('short');
        queue.batch.$('span').attr('class', 'fa fa-square-o');
      }
    }
  });
}

function initFileSetting (file, upload) {
  var queue = upload.queue;

  file.setting = new Setting({
    container: file.element.parent(),
    insert: function () {
      this.container.before(this.element);
    },
    filterData: file.data(),
    hasLink: upload.option('hasLink'),
    events: {
      show: function () {
        // 隐藏其他
        queue.getFiles().forEach(function (queueFile) {
          (queueFile !== file) &&
            queueFile.setting &&
            queueFile.setting.is(':visible') &&
            queueFile.setting.hide();
        });
        file.element.addClass('active');
      },
      hide: function () {
        file.element.removeClass('active');
      }
    }
  });

  file.initDelegates({
    'click': function () {
      if (queue.setting.is(':hidden')) {
        if (file.setting.is(':hidden')) {
          file.setting.show();
        } else {
          file.setting.hide();
        }
      }
    }
  });
}

function initThumb (file, upload) {
  var reader = new FileReader();

  reader.onload = function (e) {
    var image = new Image();

    image.onload = function () {
      // 尺寸信息
      file.role('width').text(this.width);
      file.role('height').text(this.height);
      file.role('dimens').show();

      // 预览图
      file.thumb = new Thumb({
        container: file.element,
        image: image
      });

      // 回设
      file.data({
        width: this.width,
        height: this.height
      });

      if (upload.option('process')) {
        // 设置单个处理
        initFileSetting(file, upload);
      }
    };

    image.src = e.target.result;
  };

  reader.readAsDataURL(file.option('file'));
}

module.exports = Core;

});
